Code Tracing
Manual code tracing is when the programmer interprets the results of each line of code and keeps track by hand of the effect of each statement. This type of code tracing is often faster than using a debugger to step through (trace) the execution of a program. Debuggers automate the code tracing, and you will learn about them in a later lesson. While manually tracing code is more error prone than using a debugger tool, it is a skill that all good programmers possess. This is because knowing how to manually trace a small block of code correctly does not require a programmer to run an entire program over to see the affect of a small edit in the code.
Suppose we wish to sum the odd integers from 1 to 9 using a while
loop.
Here is Matlab code to do that:
sum = 0; num = 1; while num <= 9 sum = sum + num; num = num + 2; end disp(sum)
Let's track (trace) the execution of the above code fragment. Write each variable down and keep track of (trace) the current value of the variable.
- Initialize
sum
andnum
to 0 and 1, respectively.
- Evaluate the condition expression:
(num <= 9)
- Since
num
has the value 1, the condition evaluates to true (1). - Execute the body of the loop:
sum
is updated to 1 andnum
is updated to 3.
- Evaluate the condition expression; since
num
is 3,num
<= 9 is true. - Execute the body of the loop:
sum
is updated to 4 andnum
is updated to 5.
- Evaluate the condition expression; since
num
is 5,num
<= 9 is true. - Execute the body of the loop:
sum
is updated to 9 andnum
is updated to 7.
sum: 0 1 4 9 num: 1 3 5 7
- Evaluate the condition expression; since
num
is 7,num
<= 9 is true. - Execute the body of the loop:
sum
is updated to 16 andnum
is updated to 9.
- Evaluate the condition expression; since
num
is 9,num
<= 9 is true. - Execute the body of the loop:
sum
is updated to 25 andnum
is updated to 11.
- Evaluate the condition expression; since
num
is 11,num
<= 9 is false. - Do not execute the body of the loop. Instead, control jumps to
the
disp
statement that follows theend
of the loop. - Display the final value of
sum
.
Note that you can use Matlab to help you trace the execution of the code by
removing the semicolons (;) from the code. This causes the values of sum
and num
to be displayed in the Command Window each time they are updated.
This type of output can get very long to read through, but is accurate.
Also, you can use the debugger operations to step through this code to trace its execution. Try each technique and compare the pros and cons of each. Programmers utilize lots of code tracing techniques while developing solutions to problems.
Manually tracing the execution of long loops is very time consuming. Programmers usually make the problem similar, but smaller, if the code doesn't work as intended. For instance, if the code works for 1 to 9, it should also work for 1 to 1,000,001.